import sys
sys.path.append('.')
sys.path.append('..')

from . import auth
from . import views
from . import forms
from flask import render_template,redirect,request,url_for,flash
from flask_login import current_user, login_user

from ..models import tAllUser



@auth.before_app_request
def before_request():
    if current_user.is_authenticated:
        current_user.ping()
        if not current_user.confirmed \
                and request.endpoint \
                and request.blueprint != 'auth' \
                and request.blueprint != 'admin' \
                and request.blueprint != 'main' \
                and request.endpoint != 'static':
            return redirect(url_for('auth.unconfirmed'))


@auth.route('/login',methods=['POST', 'GET'])
def login():
    name = None
    password = None
    form = forms.FormLogin()
    if form.validate_on_submit():
        user = tAllUser.query.filter_by(name=form.username.data).first()
        if user is not None and user.None_Password:
            return redirect(url_for('modifPassword'))
        if user is not None and user.verify_password(form.password.data):
            login_user(user)
            return redirect(request.args.get('next') or url_for('main.index'))
        flash('帐号密码错误！')
    return render_template('auth/login.html', form=form)

@auth.route('/modifpassword',methods=['POST', 'GET'])
def modifPassword():
    name=None
    password=None
    form = forms.FormModifPassword()
    if form.validate_on_submit():
        user = tAllUser.query.filter_by(name=form.username.data).first()
        if user is not None:
            user.password = form.password.data
        return redirect(request.args.get('next') or url_for('main.index'))
    return render_template('auth/modifpasswd.html', form=form)

